import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import { Thumbnail } from './Thumbnail.js';
import { Collapse, Tabs, List } from 'antd';
import { utils } from '@ohif/core';
import { useTranslation } from 'react-i18next';
import { ScrollableArea } from '@ohif/ui';
import StudyLoadingMonitor from '../../components/StudyLoadingMonitor';
import StudyPrefetcher from '../../components/StudyPrefetcher.js';

import './StudyBrowser.styl';

function StudyBrowser(props) {
  const {
    studies,
    onThumbnailClick,
    onThumbnailDoubleClick,
    supportsDrag,
    position,
    activeDisplaySetUID,
  } = props;

  const { t } = useTranslation("Panels");
  const [scrollableElement, setScrollableElement] = useState();
  const [currentStudyIndex, setCurrentStudyIndex] = useState(0);

  const formatPatientName = name => {
    return name ? utils.formatPN(name) : t("Unknown");
  }

  const getPanelHeader = study => {
    const { PatientName, StudyDate } = study;
    return (
      <div className="study-panel-header">
        <div className="patient-name">{formatPatientName(PatientName)}</div>
        <div className="study-date">{utils.formatDA(StudyDate)}</div>
      </div>
    );
  };

  const handleStudyChange = keys => {
    if (keys.length > 0) {
      setCurrentStudyIndex(parseInt(keys[0]));
    }
  };

  useEffect(() => {
    if (scrollableElement) {
      scrollableElement.scrollToActiveItem(document.getElementById(activeDisplaySetUID));
    }
  }, [scrollableElement, activeDisplaySetUID]);

  const getTabPaneHeader = study => {
    const { PatientName, StudyDate } = study;
    return `${formatPatientName(PatientName)} - ${utils.formatDA(StudyDate)}`;
  };

  const getStudyThumbnails = (study, studyIndex) => {
    const { StudyInstanceUID } = study;
    return (
      <>
        {study.displaySets.map((displaySet, thumbIndex) => {
          const {
            displaySetInstanceUID,
            SeriesDescription,
            numImageFrames,
            SeriesNumber,
          } = displaySet;

          let imageId;
          // let imageSrc;
          let altImageText;

          if (displaySet.Modality && displaySet.Modality === 'SEG') {
            // TODO: We want to replace this with a thumbnail showing
            // the segmentation map on the image, but this is easier
            // and better than what we have right now.
            altImageText = 'SEG';
          } else if (displaySet.images && displaySet.images.length) {
            // const imageIndex = Math.floor(displaySet.images.length / 2);
            // imageSrc = displaySet.images[imageIndex].getTagValue('baseWadoRsUri') + '/thumbnail';
            // if (process.env.NODE_ENV === 'development') {
            //   imageSrc = 'https://vw.rimagdata.com' + imageSrc;
            // }
            imageId = displaySet.images[0].getImageId();
          } else {
            altImageText = displaySet.Modality ? displaySet.Modality : 'UN';
          }

          return (
            <Thumbnail
              supportsDrag={supportsDrag}
              key={`${studyIndex}_${thumbIndex}`}
              id={`${studyIndex}_${thumbIndex}`} // Unused?
              // active={numImageFrames === thumbIndex}
              // Study
              StudyInstanceUID={StudyInstanceUID} // used by drop
              // Thumb
              altImageText={altImageText}
              imageId={imageId}
              // imageSrc={imageSrc}
              displaySetInstanceUID={displaySetInstanceUID} // used by drop
              active={activeDisplaySetUID === displaySetInstanceUID}
              numImageFrames={numImageFrames}
              SeriesDescription={SeriesDescription}
              SeriesNumber={SeriesNumber}
              // Events
              onClick={onThumbnailClick.bind(
                undefined,
                displaySetInstanceUID
              )}
              onDoubleClick={onThumbnailDoubleClick.bind(
                undefined,
                displaySetInstanceUID
              )}
            />
          );
        })}
      </>
    );
  };

  const tabBarStyle = { margin: 0 };
  if (studies.length < 2) {
    tabBarStyle.display = 'none';
  }

  return (<>{(
      position === 'top' || position === 'bottom'
    ) ? (
      // <ScrollableArea scrollX={true} scrollY={false}>
      //   <Tabs className="study-browser-tabs" keyboard="true" tabBarStyle={tabBarStyle} tabPosition='left'>
      //     {studies.map((study, studyIndex) => {
      //       return (
      //         <Tabs.TabPane tab={getPanelHeader(study)} key={studyIndex}>
      //           <List>
      //             {getStudyThumbnails(study, studyIndex)}
      //           </List>
      //         </Tabs.TabPane>
      //       )
      //     })}
      //   </Tabs>
      // </ScrollableArea>
      <ScrollableArea scrollX={true} scrollY={false} onScrollMounted={setScrollableElement}>
        <Collapse defaultActiveKey={['0']} onChange={handleStudyChange} className="study-browser horizontal-collapse">
          {studies.map((study, studyIndex) => {
            return (
              <Collapse.Panel header={getPanelHeader(study)} key={studyIndex} className="study-panel">
                <List>
                  {getStudyThumbnails(study, studyIndex)}
                </List>
              </Collapse.Panel>
            )
          })}
        </Collapse>
      </ScrollableArea>
    ) : (
      <ScrollableArea scrollX={false} scrollY={true} onScrollMounted={setScrollableElement}>
        <Collapse defaultActiveKey={['0']} onChange={handleStudyChange} className="study-browser vertical-collapse">
          {studies.map((study, studyIndex) => {
            return (
              <Collapse.Panel header={getPanelHeader(study)} key={studyIndex} className="study-panel">
                <List>
                  {getStudyThumbnails(study, studyIndex)}
                </List>
              </Collapse.Panel>
            )
          })}
        </Collapse>
      </ScrollableArea>
    )}
    <StudyLoadingMonitor studies={studies} />
    <StudyPrefetcher studies={studies} currentStudyIndex={currentStudyIndex} />
  </>);
}

const noop = () => { };

StudyBrowser.propTypes = {
  studies: PropTypes.arrayOf(
    PropTypes.shape({
      StudyInstanceUID: PropTypes.string.isRequired,
    })
  ).isRequired,
  activeDisplaySetUID: PropTypes.string,
  supportsDrag: PropTypes.bool,
  onThumbnailClick: PropTypes.func,
  onThumbnailDoubleClick: PropTypes.func,
};

StudyBrowser.defaultProps = {
  studies: [],
  supportsDrag: true,
  onThumbnailClick: noop,
  onThumbnailDoubleClick: noop,
};

export default StudyBrowser;
